// import { store } from 'quasar/wrappers'
// import { createPinia } from 'pinia'

// /*
//  * If not building with SSR mode, you can
//  * directly export the Store instantiation;
//  *
//  * The function below can be async too; either use
//  * async/await or return a Promise which resolves
//  * with the Store instance.
//  */

// export default store((/* { ssrContext } */) => {
//   const pinia = createPinia()

//   // You can add Pinia plugins here
//   // pinia.use(SomePiniaPlugin)

//   return pinia
// })
import { Login, Logout } from '../api/user';
import storage from 'store';
import { defineStore } from 'pinia';
import { GlobalState } from './interface';
import { createPinia } from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist';
import { cloneDeep } from 'lodash-es';

// import piniaPersistConfig from './interface/piniaPersist';
// import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const GlobalStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'GlobalState',
  // state: 返回对象的函数
  state: (): GlobalState => ({
    // token
    token: '',
    // userInfo
    userInfo: '',
    accountId: 0,
    menuList: [],
    permissions: [],
  }),
  getters: {},
  actions: {
    // setToken
    setToken(token: string) {
      this.token = token;
    },
    // setUserInfo
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
    },
    //权限按钮唯一标识存贮
    async setAuthButtons() {
      if (this.userInfo.ruleList && this.userInfo.ruleList.length > 0) {
        this.permissions = this.userInfo.ruleList
          .filter((item: any) => item.is_btn)
          .map((item: any) => item.view_path);
      }
    },
    //侧边菜单处理
    async setMenuList() {
      if (this.userInfo == '') {
        return;
      }
      let arr = cloneDeep(this.userInfo.ruleList);
      //按钮权限过滤
      arr = arr.filter((item: any) => item.is_btn == 0);

      // arr.forEach((i: any) => {
      //   i.icon = 'dashboard';
      // });
      const map: any = {};
      arr.forEach((v: any) => {
        map[v.id] = v;
      });

      const tree: any = [];
      arr.forEach((item: any) => {
        const mapItem = map[item.pid];
        if (mapItem) {
          (mapItem.children || (mapItem.children = [])).push(item);
        } else {
          tree.push(item);
        }
      });
      this.menuList = tree;
    },
    //清空
    clearLogin() {
      this.token = '';
      this.userInfo = '';
      this.menuList = [];
      this.permissions = [];
      // storage.set('code', code)
      storage.remove('Access-Token');
    },
    // 登录
    Login(userInfo: any) {
      return new Promise(async (resolve) => {
        const isLogin: any = await Login(userInfo);
        if (isLogin.data) {
          storage.set('Access-Token', isLogin.data.token, 60 * 60 * 1000);
          this.token = isLogin.data.token;
          this.userInfo = isLogin.data;
        }
        await this.setAuthButtons();
        await this.setMenuList();
        resolve(isLogin);
      });
    },
    // 登出
    Logout() {
      return new Promise<void>(async (resolve) => {
        await Logout();
        this.clearLogin();
        // window.location.reload()
        resolve();
      });
    },
  },
  persist: {
    enabled: true, // 启用
    strategies: [
      // storage 可选localStorage或sessionStorage
      // paths 给指定数据持久化
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userInfo', 'menuList', 'permissions'],
      },
    ],
  },
});

// piniaPersist(持久化)
const pinia = createPinia();
pinia.use(piniaPluginPersist);

export default pinia;
